import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:my_shop/util/app_sp.dart';
import 'package:flutter/services.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:my_shop/util/toast.dart';
import 'package:uuid/uuid.dart';

import 'network_util.dart';

class AppUtil {
  AppUtil._();

  static const _uuid = Uuid();
  static late String _appName;
  static late String _appVersion;
  static late String _packageName;
  static late String _appBuildNum;
  static late String _deviceId;

  static Future<void> init() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    _appName = packageInfo.appName;
    _appVersion = packageInfo.version;
    _packageName = packageInfo.packageName;
    _appBuildNum = packageInfo.buildNumber;
    _deviceId = AppSp.getDeviceId();

    if (_deviceId == '') {
      _deviceId = uuidV4();
      AppSp.putDeviceId(_deviceId);
    }
    // NetworkUtil.addNetworkListener();
    // NetworkUtil.checkNetwork();
  }

  // 基于时间的UUID
  static String uuidV1() {
    return _uuid.v1();
  }

  // 随机的UUID
  static String uuidV4() {
    return _uuid.v4();
  }

  // app名称
  static String getAppName() {
    return _appName;
  }

  // app版本
  static String getAppVersion() {
    return _appVersion;
  }

  // app构建号
  static String getAppBuildNum() {
    return _appBuildNum;
  }

  // 包名
  static String getPackageName() {
    return _packageName;
  }

  // 获取平台id
  static int getPlatform() {
    return Platform.isAndroid ? 0 : 1;
  }

  // 获取设备唯一id
  // 随机uuidV4()重复的概率极小
  static String getDeviceId() {
    return _deviceId;
  }

  // 获取md5
  static String getMD5(String data) {
    var content = const Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    return digest.toString();
  }

  // 复制到剪切板
  static void copy({required String text}) {
    Clipboard.setData(ClipboardData(text: text));
    Toast.show('复制成功');
  }
}
